from rest_auth.app_settings import create_token, TokenSerializer
from rest_auth.models import TokenModel
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView

from api.serializers.register_serializer import RegisterSerializer
from api.utils.sms.send_sms import validate_sms_code


class RegisterView(APIView):
    def post(self, request):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            # username = serializer.validated_data['username']
            # sms_code = serializer.validated_data['sms_code']
            # if not validate_sms_code(username, sms_code):
            #     raise ValidationError(u"验证码不正确或已失效")
            user = serializer.save(request)
            create_token(TokenModel, user, serializer)
            return Response(TokenSerializer(user.auth_token).data,
                            status=status.HTTP_201_CREATED)
        else:
            raise ValidationError(serializer.errors)

# class RegisterView2(CreateAPIView):
#     serializer_class = RegisterSerializer
#     permission_classes = register_permission_classes()
#     token_model = TokenModel
#
#     @sensitive_post_parameters_m
#     def dispatch(self, *args, **kwargs):
#         return super(RegisterView, self).dispatch(*args, **kwargs)
#
#     def get_response_data(self, user):
#         return TokenSerializer(user.auth_token).data
#
#
#     def create(self, request, *args, **kwargs):
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         user = self.perform_create(serializer)
#         headers = self.get_success_headers(serializer.data)
#         return Response(self.get_response_data(user),
#                         status=status.HTTP_201_CREATED,
#                         headers=headers)
#
#     def perform_create(self, serializer):
#         user = serializer.save(self.request)
#         create_token(self.token_model, user, serializer)
#         complete_signup(self.request._request, user,
#                         allauth_settings.EMAIL_VERIFICATION,
#                         None)
#         return user
